package model

import (
	"errors"
	"gorm.io/gorm"
	"shop-api/databases/mysql"
)

// User 用户表
type User struct {
	Base
	Phone          string `gorm:"type:char(11);unique;comment:'用户手机号'" json:"phone"` //唯一
	Name           string `gorm:"type:varchar(30);comment:'用户名称'" json:"name"`
	Password       string `gorm:"type:varchar(65);comment:'用户密码'" json:"password"`
	Img            string `gorm:"type:varchar(255);comment:'用户头像链接'" json:"img"`
	Status         int8   `gorm:"type:tinyint(1);default:0;comment:'用户状态（0:正常，1:禁用）'" json:"status"`
	Gender         int64  `gorm:"type:int(10);comment:'用户性别（1: 男，2: 女）'" json:"gender"`
	Birthday       string `gorm:"type:date;comment:'用户生日'" json:"birthday"`
	IgnorePassword bool   `gorm:"-"`
}

func (m *User) Create() (*User, error) {
	return m, mysql.WithClient(func(db *gorm.DB) error {
		return db.Create(m).Error
	})
}

func (m *User) Update(id uint) (*User, error) {
	err := mysql.WithClient(func(db *gorm.DB) error {
		return db.Model(m).Where("id = ?", id).Updates(m).Error
	})
	if err != nil {
		return nil, err
	}
	return m.Get(id)
}

func (m *User) Get(id uint) (*User, error) {
	info := User{}
	return &info, mysql.WithClient(func(db *gorm.DB) error {
		return db.Where("id = ?", id).First(&info).Error
	})
}

func (m *User) GetByPhone(phone string) (*User, error) {
	info := User{}
	err := mysql.WithClient(func(db *gorm.DB) error {
		err := db.Where("phone = ?", phone).First(&info).Error
		if err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		return nil, err
	}
	return &info, nil
}

func (m *User) GetByIDs(ids []uint64) ([]*User, error) {
	var infos []*User
	return infos, mysql.WithClient(func(db *gorm.DB) error {
		return db.Where("id in (?)", ids).Find(&infos).Error
	})
}

// TODO:修改某个结构体字段的值
func (u *User) AfterFind(tx *gorm.DB) (err error) {
	if u.IgnorePassword {
		u.Password = ""
	}
	return
}
func (u *User) AfterCreate(tx *gorm.DB) (err error) {
	u.Password = ""
	return
}
func (u *User) AfterUpdate(tx *gorm.DB) (err error) {
	u.Password = ""
	return
}
